package com.seeyon.apps.kk.manager;

import java.util.List;
import java.util.Map;
import javax.ws.rs.client.Client;
import javax.ws.rs.client.ClientBuilder;
import javax.ws.rs.client.Entity;
import javax.ws.rs.client.WebTarget;
import javax.ws.rs.core.MediaType;
import org.apache.commons.collections.MapUtils;
import org.apache.commons.logging.Log;
import org.apache.commons.logging.LogFactory;

import com.alibaba.fastjson.JSON;
import com.alibaba.fastjson.JSONArray;
import com.google.common.collect.Lists;
import com.google.common.collect.Maps;
import com.seeyon.ctp.organization.bo.V3xOrgDepartment;
import com.seeyon.ctp.organization.bo.V3xOrgMember;
import com.seeyon.ctp.organization.bo.V3xOrgPost;
import com.seeyon.ctp.organization.event.AddDepartmentEvent;
import com.seeyon.ctp.organization.event.AddMemberEvent;
import com.seeyon.ctp.organization.event.DeleteDepartmentEvent;
import com.seeyon.ctp.organization.event.DeleteMemberEvent;
import com.seeyon.ctp.organization.event.UpdateDepartmentEvent;
import com.seeyon.ctp.organization.event.UpdateMemberEvent;
import com.seeyon.ctp.organization.manager.OrgManager;
import com.seeyon.ctp.util.annotation.ListenEvent;
import com.seeyon.kk.utils.CoreUtils;
import com.seeyon.kk.utils.ValueUtils;

import oracle.net.aso.e;

/**
 * 向会议系统和数字档案系统添加部门和人员信息
 * 
 * @author seeyon
 *
 */
public class OrgsyncTOMeetingAndDocImpl extends BaseManager {

	private static final Log log = LogFactory.getLog(OrgsyncTOMeetingAndDocImpl.class);

	private FreemarkFlowManager freemarkFlowManager;

	private OrgManager orgManager;

	private Long accountId = 670869647114347L; // 单位Id

	public OrgManager getOrgManager() {
		return orgManager;
	}

	public void setOrgManager(OrgManager orgManager) {
		this.orgManager = orgManager;
	}

	public FreemarkFlowManager getFreemarkFlowManager() {
		return freemarkFlowManager;
	}

	public void setFreemarkFlowManager(FreemarkFlowManager freemarkFlowManager) {
		this.freemarkFlowManager = freemarkFlowManager;
	}

	@ListenEvent(event = AddMemberEvent.class, async = true)
	public void onMemberAdd(AddMemberEvent event) throws Exception {
		// meeting
		meetingMemberAdd(event.getMember());

		// email
		emailMemberAdd(event.getMember());
	}

	@ListenEvent(event = UpdateMemberEvent.class, async = true)
	public void onMemberUpdate(UpdateMemberEvent event) throws Exception {
		// meeting
		meetingMemberUpdate(event.getMember());

		// email
		emailMemberUpdate(event.getMember());
	}

	@ListenEvent(event = DeleteMemberEvent.class, async = true)
	public void onMemberDelete(DeleteMemberEvent event) throws Exception {
		// email
		emailMemberDelete(event.getMember());
	}

	@ListenEvent(event = AddDepartmentEvent.class, async = true)
	public void onDepartmentAdd(AddDepartmentEvent event) throws Exception {
		// meeting
		meetingDepartmentAdd(event.getDept());

		// email
		emailDepartmentAdd(event.getDept());
	}

	@ListenEvent(event = UpdateDepartmentEvent.class, async = true)
	public void onDepartmentUpdate(UpdateDepartmentEvent event) throws Exception {
		// meeting
		meetingDepartmentUpdate(event.getDept());

		// email
		emailDepartmentUpdate(event.getDept());
	}

	@ListenEvent(event = DeleteDepartmentEvent.class, async = true)
	public void onDeleteDepartmentDelete(DeleteDepartmentEvent event) throws Exception {
		// email
		emailDepartmentDelete(event.getDept());
	}

	/*--------------------------meeting 组织架构同步 start---------------------------*/

	public void meetingDepartmentAdd(V3xOrgDepartment dept) throws Exception {
		log.info("===================部门添加 TO Meeting===========================");
		Map<String, Object> deptMap = Maps.newHashMap();
		List<Map<String, Object>> sendMeetingList = Lists.newArrayList();
		deptMap.put("oaId", dept.getId());
		V3xOrgDepartment parentDept = this.orgManager.getDepartmentByPath(dept.getParentPath());
		if (parentDept == null)
			deptMap.put("fid", this.accountId); // 一级部门 通过ParentPath 获取不到 部门对象
		else
			deptMap.put("fid", parentDept.getId());
		deptMap.put("name", dept.getName());
		deptMap.put("pos", dept.getSortId());
		deptMap.put("delMark", dept.getIsDeleted() ? "n" : "y");
		sendMeetingList.add(deptMap);
		Client client = ClientBuilder.newClient();
		WebTarget webTarget = client.target(ValueUtils.getConfig().getString("shkk.MeetingOrgsyncUrl")).path("user")
				.path("updateDept");
		String rs = webTarget.request()
				.post(Entity.entity(JSONArray.toJSONString(sendMeetingList), MediaType.APPLICATION_JSON), String.class);
		log.info("=============》部门添加推送结果：" + rs);
	}

	public void meetingDepartmentUpdate(V3xOrgDepartment dept) throws Exception {
		log.info("===================部门修改 TO Meeting===========================");
		Map<String, Object> deptMap = Maps.newHashMap();
		List<Map<String, Object>> sendMeetingList = Lists.newArrayList();
		deptMap.put("oaId", dept.getId());
		log.info("=============>>" + dept.getParentPath());
		V3xOrgDepartment parentDept = this.orgManager.getDepartmentByPath(dept.getParentPath());
		if (parentDept == null)
			deptMap.put("fid", this.accountId); // 一级部门 通过ParentPath 获取不到 部门对象
		else
			deptMap.put("fid", parentDept.getId());
		deptMap.put("name", dept.getName());
		deptMap.put("pos", dept.getSortId());
		deptMap.put("delMark", dept.getIsDeleted() ? "n" : "y");
		sendMeetingList.add(deptMap);
		Client client = ClientBuilder.newClient();
		WebTarget webTarget = client.target(ValueUtils.getConfig().getString("shkk.MeetingOrgsyncUrl")).path("user")
				.path("updateDept");
		String rs = webTarget.request()
				.post(Entity.entity(JSONArray.toJSONString(sendMeetingList), MediaType.APPLICATION_JSON), String.class);
		log.info("=============》部门修改推送结果：" + rs);
	}

	public void meetingMemberAdd(V3xOrgMember member) throws Exception {
		log.info("===================人员添加 TO Meeting===========================");
		Map<String, Object> userMap = Maps.newHashMap();
		List<Map<String, Object>> sendMeetingList = Lists.newArrayList();
		userMap.put("delMark", member.getIsDeleted() ? "n" : "y");
		userMap.put("deptId", member.getOrgDepartmentId());
		V3xOrgPost post = this.orgManager.getPostById(member.getOrgPostId());
		userMap.put("duty", post.getName());
		userMap.put("id", member.getId());
		userMap.put("loginName", member.getLoginName());
		userMap.put("pos", member.getSortId());
		userMap.put("userName", member.getName());
		String sql = "SELECT PERSON_SECRET_LEVELS.PSL_NAME levelName,PERSON_SECRET_LEVELS.PWD_STRENGTH memlevel FROM PERSON_MEMBER_MAP LEFT JOIN PERSON_SECRET_LEVELS ON PERSON_SECRET_LEVELS.PSL_ID = PERSON_MEMBER_MAP.PSL_ID WHERE PERSON_MEMBER_MAP.MEMBER_ID = '"
				+ member.getId() + "'";
		log.info("==========》人员密级SQL" + sql);
		List<Map<String, Object>> levelList = this.jdbcTemplate.queryForList(sql);
		int secretLevel = 0;
		if (!levelList.isEmpty()) {
			Map<String, Object> levelMap = levelList.get(0);
			if (!levelMap.isEmpty()) {
				if (MapUtils.getInteger(levelMap, "memlevel") != 0)
					secretLevel = MapUtils.getInteger(levelMap, "memlevel") + 1;
				else
					secretLevel = 0;
				userMap.put("secretLevel", secretLevel);
				log.info("=============》" + member.getName() + ",密级：" + MapUtils.getString(levelMap, "levelName"));
			}
		}
		sendMeetingList.add(userMap);
		// 向会议系统推送人员信息
		if (secretLevel != -1) {
			Client client = ClientBuilder.newClient();
			WebTarget webTarget = client.target(ValueUtils.getConfig().getString("shkk.MeetingOrgsyncUrl")).path("user")
					.path("updateUser");
			String rs = webTarget.request().post(
					Entity.entity(JSONArray.toJSONString(sendMeetingList), MediaType.APPLICATION_JSON), String.class);
			log.info("=============》人员添加推送结果：" + rs);
		}
	}

	public void meetingMemberUpdate(V3xOrgMember member) throws Exception {
		log.info("===================人员修改 TO Meeting===========================");
		Map<String, Object> userMap = Maps.newHashMap();
		List<Map<String, Object>> sendMeetingList = Lists.newArrayList();
		userMap.put("delMark", member.getIsDeleted() ? "n" : "y");
		userMap.put("deptId", member.getOrgDepartmentId());
		V3xOrgPost post = this.orgManager.getPostById(member.getOrgPostId());
		userMap.put("duty", post.getName());
		userMap.put("id", member.getId());
		userMap.put("loginName", member.getLoginName());
		userMap.put("pos", member.getSortId());
		userMap.put("userName", member.getName());
		String sql = "SELECT PERSON_SECRET_LEVELS.PSL_NAME levelName,PERSON_SECRET_LEVELS.PWD_STRENGTH memlevel FROM PERSON_MEMBER_MAP LEFT JOIN PERSON_SECRET_LEVELS ON PERSON_SECRET_LEVELS.PSL_ID = PERSON_MEMBER_MAP.PSL_ID WHERE PERSON_MEMBER_MAP.MEMBER_ID = '"
				+ member.getId() + "'";
		log.info("==========》人员密级SQL" + sql);
		List<Map<String, Object>> levelList = this.jdbcTemplate.queryForList(sql);
		int secretLevel = 0;
		if (!levelList.isEmpty()) {
			Map<String, Object> levelMap = levelList.get(0);
			if (!levelMap.isEmpty()) {
				if (MapUtils.getInteger(levelMap, "memlevel") != 0)
					secretLevel = MapUtils.getInteger(levelMap, "memlevel") + 1;
				else
					secretLevel = 0;
				userMap.put("secretLevel", secretLevel);
				log.info("=============》" + member.getName() + ",密级：" + MapUtils.getString(levelMap, "levelName"));
			}
		}
		sendMeetingList.add(userMap);
		// 向会议系统推送人员信息
		if (secretLevel != -1) {
			Client client = ClientBuilder.newClient();
			WebTarget webTarget = client.target(ValueUtils.getConfig().getString("shkk.MeetingOrgsyncUrl")).path("user")
					.path("updateUser");
			String rs = webTarget.request().post(
					Entity.entity(JSONArray.toJSONString(sendMeetingList), MediaType.APPLICATION_JSON), String.class);
			log.info("=============》人员修改推送结果：" + rs);
		}
	}

	/*--------------------------meeting  end--------------------------------------*/

	/*--------------------------email 组织架构同步 start--------------------------------*/
	/**
	 * email 部门修改
	 * 
	 * @param event
	 */
	public void emailDepartmentUpdate(V3xOrgDepartment dept) throws Exception {
		log.info("=========shkk email 部门修改 start ===============");
		/**
		 * OA部门停用 email做删除处理，
		 */
		if (!dept.getEnabled()) {
			emailDepartmentDelete(dept);
		} else {
			if (getEmailOU(dept.getCode())) {
				V3xOrgDepartment parentDept = this.orgManager.getDepartmentByPath(dept.getParentPath());
				Map<String, Object> param = Maps.newHashMap();
				param.put("passkey", CoreUtils.emailMd5());
				param.put("unitou", dept.getCode());
				param.put("name", dept.getName());
				// 一级部门 通过ParentPath 获取不到 部门对象
				if (null == parentDept) {
					param.put("dunitou", ""); // email 一级部门 为空
				} else {
					param.put("dunitou", parentDept.getCode());
				}
				// eamil Url
				String urlParams = CoreUtils.buildUrlParamter(param);
				log.info("=========shkk email urlParams:" + urlParams);
				// 邮箱系统 接口有bug 修改部门分两次
				// 修改部门名称
				String neworgUrl = ValueUtils.getConfig().getString("shkk.emailUrl") + "neworg.php/org_unitedit";
				String result = CoreUtils.doGet(neworgUrl, urlParams, "UTF-8", true);
				log.info("=========shkk eamil 修改部门名称  result：" + result);
				// 移动部门
				Map<String, Object> param1 = Maps.newHashMap();
				param1.put("passkey", CoreUtils.emailMd5());
				param1.put("sou", dept.getCode());
				if (null == parentDept) {
					param1.put("dou", "");
				} else {
					param1.put("dou", parentDept.getCode());
				}
				String urlParams1 = CoreUtils.buildUrlParamter(param1);
				log.info("=========shkk email urlParams1:" + urlParams1);
				String neworgouUrl = ValueUtils.getConfig().getString("shkk.emailUrl") + "neworg.php/org_unitmove_byou";
				String newouresult = CoreUtils.doGet(neworgouUrl, urlParams1, "UTF-8", true);
				log.info("========shkk eamil 修改部门路径  newouresult：" + newouresult);
			} else {
				emailDepartmentAdd(dept);
			}
		}
	}

	/**
	 * 向 email 添加部门
	 * 
	 * @param event
	 * @throws Exception
	 */
	public void emailDepartmentAdd(V3xOrgDepartment dept) throws Exception {
		log.info("=========shkk email 部门添加 start ===============");
		V3xOrgDepartment parentDept = this.orgManager.getDepartmentByPath(dept.getParentPath());
		Map<String, Object> param = Maps.newHashMap();
		param.put("passkey", CoreUtils.emailMd5());
		param.put("unitou", dept.getCode());
		param.put("name", dept.getName());
		// 一级部门 通过ParentPath 获取不到 部门对象
		if (null == parentDept) {
			param.put("baseou", ""); // email 一级部门 为空
		} else {
			param.put("baseou", parentDept.getCode());
		}
		// eamil Url
		String urlParams = CoreUtils.buildUrlParamter(param);
		log.info("=========shkk email urlParams:" + urlParams);
		String neworgUrl = ValueUtils.getConfig().getString("shkk.emailUrl") + "neworg.php/org_unitadd";
		String result = CoreUtils.doGet(neworgUrl, urlParams, "UTF-8", true);
		log.info("=========shkk email 部门添加 result：" + result);
	}

	/**
	 * 删除email 部门
	 * 
	 * @param event
	 * @throws Exception
	 */
	public void emailDepartmentDelete(V3xOrgDepartment dept) throws Exception {
		log.info("=========shkk email Delete start ===============");
		Map<String, Object> param = Maps.newHashMap();
		param.put("passkey", CoreUtils.emailMd5());
		param.put("unitou", dept.getCode());
		// eamil Url
		String urlParams = CoreUtils.buildUrlParamter(param);
		log.info("=========shkk email delete urlParams:" + urlParams);
		String neworgUrl = ValueUtils.getConfig().getString("shkk.emailUrl") + "neworg.php/org_unitdel";
		String result = CoreUtils.doGet(neworgUrl, urlParams, "UTF-8", true);
		log.info("=========shkk email delete result：" + result);
	}

	/**
	 * 向 email 添加人员信息
	 * 
	 * @param event
	 */
	public void emailMemberAdd(V3xOrgMember member) throws Exception {
		log.info("===================shkk email memberadd start===========================");
		Map<String, Object> param = Maps.newHashMap();
		param.put("passkey", CoreUtils.emailMd5());
		param.put("mail", member.getLoginName() + ValueUtils.getConfig().getString("shkk.email"));
		param.put("name", member.getName());
		param.put("password", member.getPassword());
		param.put("host", ValueUtils.getConfig().getString("shkk.emailHost"));
		param.put("role", "2");
		V3xOrgDepartment department = this.orgManager.getDepartmentById(member.getOrgDepartmentId());
		param.put("unitou", department.getCode());
		// email 用户扩展属性
		Map<String, Object> exarrt = Maps.newHashMap();
		exarrt.put("extauthid", member.getCode());
		exarrt.put("status", member.getEnabled() ? 1 : 2);
		// 人员密级
		String sqlLevel = "SELECT PERSON_SECRET_LEVELS.PWD_STRENGTH mj FROM PERSON_SECRET_LEVELS LEFT JOIN PERSON_MEMBER_MAP ON PERSON_MEMBER_MAP.PSL_ID = PERSON_SECRET_LEVELS.PSL_ID WHERE PERSON_MEMBER_MAP.MEMBER_ID = '"
				+ member.getId() + "'";
		log.info("==========shkk email ======》人员密级SQL:" + sqlLevel);
		List<Map<String, Object>> levelList = this.jdbcTemplate.queryForList(sqlLevel);
		int secretLevel = 0;
		if (!levelList.isEmpty()) {
			Map<String, Object> levelMap = levelList.get(0);
			if (!levelMap.isEmpty()) {
				secretLevel = MapUtils.getInteger(levelMap, "mj");
				log.info("=============shkk email====》" + member.getName() + ",密级：" + secretLevel);
			}
		}
		exarrt.put("mj", secretLevel);
		param.put("extattr", exarrt.toString().replace("{", "").replace("}", "").replace(" ", ""));
		// eamil Url
		String urlParams = CoreUtils.buildUrlParamter(param);
		log.info("=========shkk email memberadd urlParams:" + urlParams);
		String neworgUrl = ValueUtils.getConfig().getString("shkk.emailUrl") + "neworg.php/org_adduser";
		String result = CoreUtils.doGet(neworgUrl, urlParams, "UTF-8", true);
		log.info("=========shkk email memberadd end result：" + result);
	}

	/**
	 * email 修改人员信息
	 * 
	 * @param event
	 */
	public void emailMemberUpdate(V3xOrgMember member) throws Exception {
		log.info("===================shkk email memberupdate start===========================");
		String email = member.getLoginName() + ValueUtils.getConfig().getString("shkk.email");
		if (!member.getEnabled()) {
			emailMemberDelete(member);
		} else {
			if (getEmailUser(email)) {
				Map<String, Object> param = Maps.newHashMap();
				param.put("passkey", CoreUtils.emailMd5());
				param.put("user", email);
				V3xOrgDepartment department = this.orgManager.getDepartmentById(member.getOrgDepartmentId());
				param.put("unitou", department.getCode());
				// email 用户扩展属性
				Map<String, Object> exarrt = Maps.newHashMap();
				exarrt.put("extauthid", member.getCode());
				exarrt.put("status", member.getEnabled() ? 1 : 2);
				// 人员密级
				String sqlLevel = "SELECT PERSON_SECRET_LEVELS.PWD_STRENGTH mj FROM PERSON_SECRET_LEVELS LEFT JOIN PERSON_MEMBER_MAP ON PERSON_MEMBER_MAP.PSL_ID = PERSON_SECRET_LEVELS.PSL_ID WHERE PERSON_MEMBER_MAP.MEMBER_ID = '"
						+ member.getId() + "'";
				log.info("==========shkk email  ======》人员密级SQL:" + sqlLevel);
				List<Map<String, Object>> levelList = this.jdbcTemplate.queryForList(sqlLevel);
				int secretLevel = 0;
				if (!levelList.isEmpty()) {
					Map<String, Object> levelMap = levelList.get(0);
					if (!levelMap.isEmpty()) {
						secretLevel = MapUtils.getInteger(levelMap, "mj");
						log.info("=============shkk email====》" + member.getName() + ",密级：" + secretLevel);
					}
				}
				exarrt.put("mj", secretLevel);
				param.put("extattr", exarrt.toString().replace("{", "").replace("}", "").replace(" ", ""));
				// eamil Url
				String urlParams = CoreUtils.buildUrlParamter(param);
				log.info("=========shkk email memberupdate urlParams:" + urlParams);
				String neworgUrl = ValueUtils.getConfig().getString("shkk.emailUrl")
						+ "neworg.php/org_userchangeandmove";
				String result = CoreUtils.doGet(neworgUrl, urlParams, "UTF-8", true);
				log.info("=========shkk email memberupdate end result：" + result);
			} else {
				emailMemberAdd(member);
			}
		}
	}

	/**
	 * 删除email用户
	 * 
	 * @param event
	 * @throws Exception
	 */
	public void emailMemberDelete(V3xOrgMember member) throws Exception {
		log.info("===================shkk email delete start===========================");
		Map<String, Object> param = Maps.newHashMap();
		param.put("passkey", CoreUtils.emailMd5());
		param.put("user", member.getLoginName() + ValueUtils.getConfig().getString("shkk.email"));
		// eamil Url
		String urlParams = CoreUtils.buildUrlParamter(param);
		log.info("=========shkk email memberadd urlParams:" + urlParams);
		String neworgUrl = ValueUtils.getConfig().getString("shkk.emailUrl") + "neworg.php/org_deluser";
		String result = CoreUtils.doGet(neworgUrl, urlParams, "UTF-8", true);
		log.info("=========shkk email delete end result：" + result);
	}

	/**
	 * 验证email 部门是否存在
	 * 
	 * @param ou
	 * @return
	 */
	public boolean getEmailOU(String deptCode) {
		log.info("==================shkk email getEmailOU start===========================");
		Map<String, Object> param = Maps.newHashMap();
		param.put("passkey", CoreUtils.emailMd5());
		param.put("unitou", deptCode);
		// eamil Url
		String urlParams = CoreUtils.buildUrlParamter(param);
		log.info("=========shkk email getEmailOU urlParams:" + urlParams);
		String neworgUrl = ValueUtils.getConfig().getString("shkk.emailUrl") + "neworg.php/get_unit_byou";
		String result = CoreUtils.doGet(neworgUrl, urlParams, "UTF-8", true);
		Map<String, Object> rsMap = JSON.parseObject(result);
		log.info("=========shkk email getEmailOU end result：" + result);
		if (MapUtils.getString(rsMap, "errcode").equals("0"))
			return true;
		else
			return false;
	}

	/**
	 * 验证email 用户是否存在
	 * 
	 * @param email
	 * @return
	 */
	public boolean getEmailUser(String email) {
		log.info("===================shkk email getEmailUser start===========================");
		Map<String, Object> param = Maps.newHashMap();
		param.put("passkey", CoreUtils.emailMd5());
		param.put("user", email);
		param.put("is_ex", "yes");
		// eamil Url
		String urlParams = CoreUtils.buildUrlParamter(param);
		log.info("=========shkk email getEmailUser urlParams:" + urlParams);
		String neworgUrl = ValueUtils.getConfig().getString("shkk.emailUrl") + "neworg.php/org_userget";
		String result = CoreUtils.doGet(neworgUrl, urlParams, "UTF-8", true);
		Map<String, Object> rsMap = JSON.parseObject(result);
		log.info("=========shkk email getEmailUser end result：" + result);
		if (MapUtils.getString(rsMap, "errcode").equals("0"))
			return true;
		else
			return false;
	}
	/*----------------------------email end-----------------------------------*/
}
